const parallelLimit = require('run-parallel-limit')
const path = require("path");
const upload_single = require("./upload-single")
const speedtest = require("./speedtest");

/**
 * 
 * @param {String[]} full_paths 
 * @param {Number} max_uploads 
 */
function upload(full_paths, max_uploads) {
  let paths = Array.from(full_paths);
  return new Promise((resolve) => {
    let errors_occured = [];
    let tasks = paths.map(full_path => {
      return cb => {
        upload_single.uploadSingleForXTime(3, full_path).then((o) => {
          if (o.ok) {
            console.log(path.basename(full_path));
            console.log(o.url);
          }else{
            let err = {
              full_path:full_path,
              error:o.msg
            };
            errors_occured.push(err);
          }
          cb(null, full_path);
        })
      }
    });

    parallelLimit(tasks, max_uploads, function (err, results) {
      console.log("\n\n parallel tasks done..");
      if(errors_occured.length){
        console.error("Errors happened: ",errors_occured);
      }
      resolve();

    })
  })

}

module.exports = {
  upload: upload,
  upload_single,
  speedtest
}